import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select,Tooltip} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import { template,templateInsert,templateUpdate,Delete} from "@/api/modules/report";
import { upload } from "@/api/modules/common";

const Template = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [onReloadNum,setOnReloadNum] = useState(null)
  const formColumns = []

  const columns: any = [
    {
      title: t('template.name'),
      dataIndex: 'name',
      key: 'name',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (name) => (
        <Tooltip placement="topLeft" title={name}>
          {name}
        </Tooltip>
      ),
    },
    {
      title:t('template.id'),
      dataIndex: 'id',
      key: 'id',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (id) => (
        <Tooltip placement="topLeft" title={id}>
          {id}
        </Tooltip>
      ),
    },
    {
      title: t('template.file'),
      dataIndex: 'file',
      key: 'file',
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (file) => (
        <Tooltip placement="topLeft" title={file}>
          {file}
        </Tooltip>
      ),
    },
    {  
      title: ('action'),  
      key: 'action',  
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleDownload(record)}>  
           {t('download')}  
          </Button> 
          <Button type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>  
          <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>  
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await template({...formData, orderby: 'id', order: 0})
    if(!success) return false
    console.log(data)
    const list = data
    list.forEach(element => {
      let rmk = element.file
      rmk = rmk.replace("api","res-dir")
      element.file=rmk
    }); 
    return {
      data: list,
      total: list.length
    }
  } 

  const handleAdd = () =>{
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    let formData = new FormData();
    formData.append('file',filename); // 假设file.file是选中的文件对象  
    if(Title=='新增/New'){
       
    }else{
        formData.append("id", values.id);
    }
    formData.append("name", values.name);
    if(Title=='新增/New'){
        //新增
        templateInsert(formData).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        templateUpdate(formData).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleDownload = (row) =>{
    let file = row.file.split('/');
    let filename=file[file.length-1]
    let a = document.createElement('a');//在dom树上创建一个a标签
    let url = '/res-dir/ReportTemplate/'+filename
    console.log(url);
    a.href = url;//将url赋值给a标签的href属性
    a.download = filename;//设置设置下载文件的名称
    a.click();//主动触发a标签点击事件
  }

  const handleEdit = (record) =>{
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    var formData = new FormData();
    formData.append("id", key);
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        Delete(formData).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const beforeUpload = (file) => {  
   
  };  

const handleFileChange = (info) => { 
    console.log(info,'info') 
    form.setFieldsValue({  
        file: info.file,  
      }); 
  };  

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}
          destroyOnClose  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled />  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="name"  
              label={t('template.name')}  
              rules={[{ required: true, message: '请输入名称！' }]}  
            >  
              <Input/>  
            </Form.Item>  
            <Form.Item  
                name="file"  
                label={t('template.file')}
            >  
                <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                  let formData = new FormData();
                  formData.append("file", file);
                  const target = "ReportTemplate"//存放文件路径
                  formData.append("target", target);
                  upload(formData).then(res=>{
                     console.log(res.data.data)
                     setFilename(res.data.data)
                  })
                    // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                    // 例如，使用axios发送POST请求上传文件  
                    // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                beforeUpload={beforeUpload}  
                onChange={handleFileChange} 
                >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
                </Upload>  
            </Form.Item>
          </Form>  
        </Modal>  
    </div>
  )
}
export default Template
